import React from 'react';
import { useFormik } from 'formik';
import { Link } from 'react-router-dom';

const FormikDemo = () => {
  const formik = useFormik({
    initialValues: {
      username: '',
      password: ''
    },

    validate: values => {
      const errors = {};
      if (!values.username) {
        errors.username = '输入用户名';
      } else if (values.username.length > 10) {
        errors.username = '用户名的长度不能大于10';
      }

      if (values.password.length > 6) {
        errors.password = '密码长度不能超过6位';
      }

      return errors;
    },

    onSubmit: valuse => console.log(valuse)
  });
  return (
    <>
      <h1>formik的使用</h1>
      <form onSubmit={formik.handleSubmit}>
        <input type="text" name="username" {...formik.getFieldProps('username')} />
        <p>{(formik.touched.username && formik.errors.username) ?? null}</p>
        <input type="password" name="password" {...formik.getFieldProps('password')} />
        <p>{(formik.touched.password && formik.errors.password) ?? null}</p>
        <input type="submit" />
      </form>

      <Link to="/formik/yup">fromik yup demo</Link>
    </>
  );
};

export default FormikDemo;
